package com.godyao.security.jwt.config;

import com.godyao.security.jwt.filter.JwtAuthenticationLoginFilter;
import com.godyao.security.jwt.handler.LoginAuthenticationFailureHandler;
import com.godyao.security.jwt.handler.LoginAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author godyao
 * @date 2022/3/16
 */
@Configuration
public class JwtAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private LoginAuthenticationSuccessHandler loginAuthenticationSuccessHandler;

    @Autowired
    private LoginAuthenticationFailureHandler loginAuthenticationFailureHandler;

    /**
     * 加密
     */

    @Lazy
    @Autowired
    private PasswordEncoder passwordEncoder;


    /**
     * 将登录接口的过滤器配置到过滤器链中
     * @param builder
     */
    @Override
    public void configure(HttpSecurity builder) {
        final JwtAuthenticationLoginFilter jwtAuthenticationLoginFilter = new JwtAuthenticationLoginFilter();
        jwtAuthenticationLoginFilter.setAuthenticationManager(builder.getSharedObject(AuthenticationManager.class));
        jwtAuthenticationLoginFilter.setAuthenticationSuccessHandler(loginAuthenticationSuccessHandler);
        jwtAuthenticationLoginFilter.setAuthenticationFailureHandler(loginAuthenticationFailureHandler);
        //直接使用DaoAuthenticationProvider
        final DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        //设置userDetailService
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        //设置加密算法
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        builder.authenticationProvider(daoAuthenticationProvider);
        //将这个过滤器添加到UsernamePasswordAuthenticationFilter之前执行
        builder.addFilterBefore(jwtAuthenticationLoginFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
